import React, { useState, useEffect } from 'react';
import { View, Text, Image, StyleSheet, FlatList, TouchableOpacity, Switch, Button, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { get, post } from '../http/http';
import ImageConstants from '../resources/ImageConstants';


const GroupComponent = ({ title, children }) => {
  const styles = StyleSheet.create({
    group: {
      marginBottom: 20,
      backgroundColor: '#61c6a4',
      borderRadius: 10,
      paddingTop: 15,
    },
    groupTitle: {
      fontSize: 18,
      color: 'white',
      fontWeight: 'bold',
      marginBottom: 10,
      marginHorizontal: 15,
    },
    groupContent: {
      // 这里可以添加更多样式来调整内容的布局
      backgroundColor: 'white',
    },
  });
  return (
    <View style={styles.group}>
      <Text style={styles.groupTitle}>{title}</Text>
      <View style={styles.groupContent}>
        {children}
      </View>
    </View>
  );
};


const ClassroomScreen = ({ route }) => {
  const { classroomId, classroomName } = route.params;
  const [airConditions, setAirConditions] = useState([]);
  const [devices, setDevices] = useState([]);
  const [controlDevices, setControlDevices] = useState([]);
  const [controls, setControls] = useState([]);
  const [lightingList, setLightingList] = useState([]);
  const [airConditionDevices, setAirConditionDevices] = useState([]);
  const navigation = useNavigation();

  useEffect(() => {
    loadData();
    navigation.setOptions({ title: classroomName });
  }, []);

  const loadData = async () => {
    try {
      const data = await get('security/securityStatistical/api/getClassroomEquipmentData', { classroomId });
      const result = await get('security/zdAircondition/api/getClassroomAirconditionList', { classroomId });
      const result2 = await get('security/zdLighting/api/getClassroomLightingList', { classroomId });
      setAirConditions(data.data.classroomEquipmentList.filter((v) => v.typeNum === '000003'));
      setDevices(data.data.classroomEquipmentList.filter((v) => v.controlType === 1));
      setControlDevices(data.data.classroomEquipmentList.filter((v) => v.controlType === 0));
      setControls(data.data.controlList);
      setAirConditionDevices(result.data);
      setLightingList(result2.data);
    } catch (error) {
      console.log(error);
    }
  };

  const updateEqumentValue = async (equ: any) => {
    try {
      await post('security/equipmentInfo/api/sendInstructions', {
        equipmentId: equ.equipmentId,
        classroomId,
        messageType: 0,
        isOpen: equ.isOpen ? 0 : 1,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const change = async (e: boolean, equ: any) => {
    try {
      await post('security/equipmentInfo/api/sendInstructions', {
        classroomId,
        isOpen: e,
        equipmentId: equ.equipmentId,
        messageType: 0,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const operateAircondition = async (e: number, equ: any) => {
    try {
      await post('security/zdAircondition/api/operateAircondition', {
        configId: equ.configId,
        val: e,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const operateLighting = async (e, equ) => {
    try {
      await post('security/zdLighting/api/operateLighting', {
        configId: equ.configId,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const navigateTo = (screen, params) => {
    navigation.navigate(screen, params);
  };

  const activate = (isOpen: boolean) => {
    post('security/securityStatistical/api/roomSendInstructions', {
      classroomId,
      isOpen,
    }).then(() => {
      loadData();
    }).catch((error) => {
      Alert.alert('Error', error.message);
    });
  };


  const updateAirCondition = async (airCondition, command) => {
    try {
      await post('security/equipmentInfo/api/sendInstructions', {
        classroomId,
        equipmentId: airCondition.equipmentId,
        instructions: command,
      });
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.row}>
        <TouchableOpacity style={styles.col} onPress={() => navigateTo('ReviewScreen', { classroomId })}>
          <Image source={ImageConstants.BTN_INDEX1} style={{ width: 103, height: 78 }} resizeMode="contain" />
        </TouchableOpacity>
        <TouchableOpacity style={styles.col} onPress={() => navigateTo('RoomsiteScreen', { classroomId })}>
          <Image source={ImageConstants.BTN_INDEX2} style={{ width: 103, height: 78 }} resizeMode="contain" />
        </TouchableOpacity>
        <TouchableOpacity style={styles.col} onPress={() => navigateTo('DeviceFixScreen', { classroomId })}>
          <Image source={ImageConstants.BTN_INDEX3} style={{ width: 103, height: 78 }} resizeMode="contain" />
        </TouchableOpacity>
      </View>

      <View style={styles.row}>
        <TouchableOpacity style={styles.col} onPress={() => activate(1)}>
          <Image source={ImageConstants.BTN_ROOM1} style={styles.image} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.col} onPress={() => activate(0)}>
          <Image source={ImageConstants.BTN_ROOM2} style={styles.image} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.col} onPress={() => navigateTo('VideoScreen', { classroomId })}>
          <Image source={ImageConstants.BTN_ROOM3} style={styles.image} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.col} onPress={() => navigateTo('ReserveScreen', { classroomId })}>
          <Image source={ImageConstants.BTN_ROOM4} style={styles.image} />
        </TouchableOpacity>
      </View>

      <View style={styles.content}>
        {airConditions.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>空调控制</Text>
            {airConditions.map((airCondition) => (
              <GroupComponent title={'空调调温器'} key={airCondition.equipmentId}>
                <View key={airCondition.equipmentId} style={styles.group}>
                  <View style={styles.groupHeader}>
                    <Text>{airCondition.rangeVal === 0 ? '空闲' : airCondition.rangeVal === 0.2 ? '制热' : '制冷'}</Text>
                    <Text style={{ color: airCondition.isOnLine ? '#00FF7E' : 'red', margin: 'auto 10px' }}>
                      ● {airCondition.isOnLine ? '在线' : '离线'}
                    </Text>
                  </View>
                  <View style={styles.row}>
                    <Button title="制冷开机" onPress={() => updateAirCondition(airCondition, 0)} />
                    <Button title="制冷关机" onPress={() => updateAirCondition(airCondition, 1)} />
                    <Button title="制热开机" onPress={() => updateAirCondition(airCondition, 2)} />
                    <Button title="制热关机" onPress={() => updateAirCondition(airCondition, 3)} />
                  </View>
                </View>
              </GroupComponent>
            ))}

            {airConditionDevices.map((airCondition) => (
              <GroupComponent title={airCondition.locationName} key={airCondition.equipmentId}><View key={airCondition.equipmentId} style={styles.group}>
                <View style={styles.groupHeader}>
                  <Text>{airCondition.online === 1 && airCondition.airconditionState === 0 ? '关闭' : ''}</Text>
                  <Text>{airCondition.online === 1 && airCondition.airconditionState === 1 ? '开启' : ''}</Text>
                  <Text style={{ color: airCondition.online ? '#00FF7E' : 'red', margin: 'auto 10px' }}>
                    ● {airCondition.online ? '在线' : '离线'}
                  </Text>
                </View>
                <View style={styles.row}>
                  <Switch
                    value={!!airCondition.airconditionState}
                    disabled={airCondition.online === 0}
                    onValueChange={(value) => operateAircondition(value ? 1 : 0, airCondition)}
                  />
                </View>
              </View></GroupComponent>
            ))}
          </View>
        )}

        {devices.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>环境监测</Text>
            <View style={styles.group}>
              {devices.map((equ) => (
                <View key={equ.name} style={styles.groupItem}>
                  <Text style={styles.groupItemText}>{equ.name}: {equ.value}{equ.unitName || ''}</Text>
                  <Text style={{ color: equ.isOnLine ? '#00FF7E' : 'red', margin: 'auto 10px' }}>
                    ● {equ.isOnLine ? '在线' : '离线'}
                  </Text>
                </View>
              ))}
            </View>
          </View>
        )}

        {controlDevices.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>教室设备控制</Text>
            <View style={styles.group}>
              {controlDevices.map((equ) => (
                <View key={equ.name} style={styles.groupItem}>
                  <Text style={styles.groupItemText}>{equ.name}: {equ.isOpen ? '已打开' : '未打开'}</Text>
                  <Switch
                    value={equ.isOpen}
                    onValueChange={(value) => change(value, equ)}
                  />
                </View>
              ))}
              {lightingList.map((equ) => (
                <View key={equ.name} style={styles.groupItem}>
                  <Text style={styles.groupItemText}>{equ.locationName}: {equ.online ? '在线' : '离线'}</Text>
                  <Switch
                    value={equ.lightingState}
                    onValueChange={(value) => operateLighting(value, equ)}
                    disabled={!equ.online}
                  />
                </View>
              ))}
            </View>
          </View>
        )}

        {controls.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>教室门禁状态</Text>
            <GroupComponent title={'设备列表'}>
              <View style={styles.group}>
                {controls.map((equ) => (
                  <View key={equ.locationName} style={styles.groupItem}>
                    <Text style={styles.groupItemText}>{equ.locationName}: {equ.online ? '在线' : '离线'}</Text>
                    <Button
                      title="开门"
                      onPress={() => updateEqumentValue(equ)}
                      disabled={!equ.online}
                    />
                  </View>
                ))}
              </View>
            </GroupComponent>

          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F8F8',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 10,
  },
  col: {
    flex: 1,
    alignItems: 'center',
  },
  image: {
    width: 80,
    height: 80,
  },
  content: {
    padding: 15,
    flex: 1,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  group: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 15,
  },
  groupHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 10,
  },
  groupItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  groupItemText: {
    flex: 1,
  },
});

export default ClassroomScreen;
